package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import org.springframework.data.mongodb.core.query.Update;
import sun.reflect.annotation.TypeAnnotation;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;
    @Override
    public String publish(Movement movement) {
        try {
            //保存动态详情 设置pid
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //查询当前用户的好友信息
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            //忽略事务
            e.printStackTrace();
        }
        return movement.getId().toHexString();
    }

    @Autowired
    private TimeLineService timeLineService;


    /**
     * 首页动态
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = new Query(criteria);
        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, 0, movements);
    }

    /**
     * 查询好友动态
     *
     * @param friendId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> findmovements(Long friendId, Integer page, Integer pagesize) {
        //根据friendId查询时间线表
        Query query = new Query(Criteria.where("friendId").is(friendId))
                .skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //提取动态id列表
        List<ObjectId> friends = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //根据动态id查询动态详情
        Query movements = new Query(Criteria.where("id").in(friends).and("state").is(1));
        return mongoTemplate.find(movements, Movement.class);
    }

    /**
     * 推荐好友
     *
     * @param pids
     * @return
     */
    @Override
    public List<Movement> findmovementsById(List<Long> pids) {
        Query query = new Query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * redis中如果有数据，直接推荐好友动态信息
     *
     * @param movementId
     * @return
     */
    @Override
    public Movement findByid(String movementId) {
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        return movement;
    }

    /**
     * 根据id动态分页查询
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */
    @Override
    public List<Movement> findMessages(Integer page, Integer pagesize, Long uid, Integer state) {
        Query query = new Query();
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        //查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //查询数据列表，设置分页参数，排序
        query.with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page - 1) * pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
//        return new PageResult(page, pagesize, (int) count, list);
        return list;
    }

    /**
     * 更新动态状态
     * @param movementId
     * @param state
     */
    @Override
    public void update(String movementId, int state) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }


    /**
     * 如果redis中没有好友动态数据，随机推荐好友动态
     *
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        TypedAggregation annotation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pagesize));
        AggregationResults<Movement> results = mongoTemplate.aggregate(annotation, Movement.class);
        return results.getMappedResults();
    }
}
